#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "JsonNode.h"


JsonNode::JsonNode()
{
}

JsonNode::~JsonNode()
{
}
TxtNode::TxtNode()
{
	value = NULL;
}
TxtNode::TxtNode(const char * s)
{
	value = strdup(s);
}
TxtNode::~TxtNode()
{
	if( value ) delete value;
}
void TxtNode::print(FILE *out,int level)
{
	fprintf(out,"%s",value);
}

PairNode::PairNode()
{
	name = NULL;
	value = NULL;
}
PairNode::PairNode(const char *s)
{
	name = strdup(s);
	value = NULL;
}
PairNode::~PairNode()
{
	if( name ) delete name;
	if( value ) delete value;
}
void PairNode::print(FILE * out,int level)
{
	fprintf(out,"%s:",name);
	value->print(out,level);
}
BraceNode::BraceNode()
{
}
BraceNode::~BraceNode()
{
	for(int i=0;i<nodes.GetSize();i++) if( nodes.GetAt(i) ) delete (JsonNode *)(nodes.GetAt(i));
	nodes.RemoveAll();
}
void BraceNode::print(FILE *out,int level)
{
	if( nodes.GetSize()>0 ){
		if( nodes.GetSize()>1 )	fprintf(out,"{\n%*s",level+2,"");
		else fprintf(out,"{ ");
		((JsonNode*)nodes.GetAt(0))->print(out,level+2);
		for(int i=1;i<nodes.GetSize();i++) {
			fprintf(out,",\n%*s",level+2,"");
			((JsonNode*)nodes.GetAt(i))->print(out,level+2);
		}
		if( nodes.GetSize()>1 ) fprintf(out,"\n%*s}",level,"");
		else fprintf(out," }");
		return;
	}
	fprintf(out,"{}");
}
SquareNode::SquareNode()
{
}
SquareNode::~SquareNode()
{
}
void SquareNode::print(FILE * out,int level)
{
	if( nodes.GetSize()>0 ){
		if( nodes.GetSize()>1 )	fprintf(out,"[\n%*s",level+2,"");
		else fprintf(out,"[ ");
		((JsonNode*)nodes.GetAt(0))->print(out,level+2);
		for(int i=1;i<nodes.GetSize();i++){
			fprintf(out,",\n%*s",level+2,"");
			((JsonNode*)nodes.GetAt(i))->print(out,level+2);
		}
		if( nodes.GetSize()>1 ) fprintf(out,"\n%*s]",level,"");
		else fprintf(out," ]");
		return;
	}
	fprintf(out,"[]");
}
